<template>
  <div>
    <el-button type="primary" @click="open">{{ $t('common.upload') }}</el-button>
    <el-button type="primary" v-debounce="exportExcalOk">{{ $t('common.export') }}</el-button>
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="$t('common.upload')"
      width="30%"
      draggable
      @close="closeDialog"
    >
      <span>
        <T_Upload v-model:file-list="fileList">
          <template #tip>
            <div
              v-html="
                $t('upload.only_upload', { type: `<span style='color: red'>.xlsx,.xls</span>` })
              "
            ></div>
          </template>
        </T_Upload>
      </span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">{{ $t('common.isNo') }}</el-button>
          <el-button type="primary" @click="isOk">
            {{ $t('common.isOk') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
    <div v-if="tableTypeData.type && tableTypeData.type.length" class="titleLabel">
      {{ tableTypeData.name }}
    </div>
    <T_Table
      v-if="tableTypeData.type && tableTypeData.type.length"
      :table-type="tableTypeData.type"
      :data="(tableTypeData.data as unknown[])"
    ></T_Table>
  </div>
</template>
<script lang="ts" setup name="Excal">
import { TablePropType } from '@/interfaces/Element/Table'
import { readExcel, exportExcelFile } from '@/utils/excal'
import { UploadUserFile } from 'element-plus'
interface TableRowType {
  Domain: string
  IP_Address: string
  TTL: number
  Type: 'A' | 'B'
}
interface TableType {
  name: string
  type: Array<TablePropType> | null
  data: unknown[] | null
}
const fileList = ref<UploadUserFile[]>()
const dialogVisible = ref<boolean>(false)
const tableTypeData = reactive<TableType>({
  name: '数据',
  type: null,
  data: null
})
const open = () => {
  tableTypeData.type = null
  tableTypeData.data = null
  dialogVisible.value = true
}
const exportExcalOk = () => {
  const data = [
    {
      姓名: 'zhangsan',
      年龄: 20,
      性别: '男'
    },
    {
      姓名: 'zhangsan',
      年龄: 20,
      性别: '男'
    }
  ]
  exportExcelFile(data, '导出模板.xlsx')
}
const closeDialog = () => {
  dialogVisible.value = false
  fileList.value = []
}
const isOk = async () => {
  tableTypeData.name = fileList.value![0].raw!.name
  const result: Array<TableRowType> = (await readExcel(
    fileList.value![0].raw
  )) as Array<TableRowType>
  tableTypeData.type = []
  for (const key in result[0]) {
    tableTypeData.type.push({
      prop: key,
      label: key
    })
  }
  tableTypeData.data = result
  closeDialog()
}
</script>
<style lang="scss"></style>
